import java.awt.event.ComponentListener;

public class Complex {
    // 定义属性并生成getter,setter
    double RealPart;
    double ImagePart;
    // 定义构造函数
    public Complex(){
        RealPart=0;
        ImagePart=0;
    }
    public Complex(double R,double I){
        RealPart=R;
        ImagePart=I;
    }

    //Override Object
    @Override
    public boolean equals(Object obj){
        if(obj instanceof Complex){
            if (doubleFormat(((Complex) obj).ImagePart).equals(doubleFormat(this.ImagePart))
                    && doubleFormat(((Complex) obj).RealPart).equals(doubleFormat(this.RealPart))){
                return true;
            }
            else {
                return false;
            }
        }
        else {
            return false;
        }
    }
    @Override
    public String toString(){
        if (this.ImagePart>0) {
            return doubleFormat(this.RealPart)+"+"+doubleFormat(this.ImagePart)+"i";
        }else if(this.ImagePart<0){
            return doubleFormat(this.RealPart)+""+doubleFormat(this.ImagePart)+"i";
        }else {
            return doubleFormat(this.RealPart);
        }
    }

    // 定义公有方法:加减乘除
    Complex ComplexAdd(Complex a){
        double realresult;
        double imageresult;
        realresult = this.RealPart+a.RealPart;
        imageresult = this.ImagePart+a.ImagePart;
        return new Complex(realresult,imageresult);
    }
    Complex ComplexSub(Complex a){
        double realresult;
        double imageresult;
        realresult = this.RealPart-a.RealPart;
        imageresult = this.ImagePart-a.ImagePart;
        return new Complex(realresult,imageresult);
    }
    Complex ComplexMulti(Complex a){
        double realresult;
        double imageresult;
        realresult = this.RealPart*a.RealPart-this.ImagePart*a.ImagePart;
        imageresult = this.RealPart*a.ImagePart+this.ImagePart*a.RealPart;
        return new Complex(realresult,imageresult);
    }
    Complex ComplexDiv(Complex a) throws ComplexDivideZeroException{
        double realresult;
        double imageresult;
        if (a.ImagePart==0 && a.RealPart==0){
            throw new ComplexDivideZeroException("除数不能为0");
        }
        realresult = (this.RealPart*a.RealPart+this.ImagePart*a.ImagePart)/
                (a.ImagePart*a.ImagePart+a.RealPart*a.RealPart);
        imageresult = (this.ImagePart*a.RealPart-this.RealPart*a.ImagePart)/
                (a.ImagePart*a.ImagePart+a.RealPart*a.RealPart);
        return new Complex(realresult,imageresult);
    }

    String doubleFormat(double num){
        return String.format("%.2f",num);
    }

    public class ComplexDivideZeroException extends Exception{
        ComplexDivideZeroException(String msg){
            super(msg);
        }
    }
}